import java.util.Arrays;

public class ArrayList implements IA{
    private int[] array;
    private int index = 0;

    public void checkpos(int pos) throws PosIllegal{
        if (pos < 0 || pos > array.length){
            throw new PosIllegal("pos位置不合法");
        }
    }

    public void checkempty() throws EmptyException{
        if (index == 0){
            throw new EmptyException("顺序表为空");
        }
    }

    public ArrayList(int size) {
        this.array = new int[size];
    }
    public boolean isFull() {
        return index == array.length;
    }

    public void Display(){
        for (int i = 0; i < array.length; i++) {
            if (array[i] != 0) {
                System.out.print(array[i] + " ");
            }
        }
    }

    public void Add(int value) {

        if (isFull()){
            this.array = Arrays.copyOf(array, array.length * 2);
        }

        array[index] = value;
        index++;
    }

    public void Add(int pos , int value) {
        try{
            checkpos(pos);
            if (isFull()){
                this.array = Arrays.copyOf(array, array.length * 2);
            }

            for (int i = index; i >= pos; i--) {
                array[i] = array[i-1];
            }

            array[pos] = value;
            index++;
        }catch (PosIllegal e){
            System.out.println("插入元素位置不合法");
            e.printStackTrace();
        }

    }

    public int getIndex(){
        return this.index;
    }
//是否包含这个元素
    public boolean contains(int toFind){
        for (int i = 0; i < array.length; i++) {
            if (array[i] == toFind) {
                return true;
            }
        }
        return false;
    }

    public int indexOf(int toFind){
        for (int i = 0; i < array.length; i++) {
            if (array[i] == toFind) {
                return i;
            }
        }
        return -1;
    }

    public void set(int pos, int value){
        try {
            checkempty();
            array[pos] = value;
        }catch (EmptyException e){
            System.out.println("顺序表为空");
            e.printStackTrace();
        }
    }

    public int get(int pos){
        return array[pos];
    }

    public void remove(int toRemove){
        int pos = indexOf(toRemove);
        for (int i = pos; i <index - 1; i++) {
            array[i] = array[i+1];
        }
        index--;
    }

    public void clear(){
        index = 0;
    }
}
